<template>
  <div>
    <div>待发布新闻（{{ releaseList.length }}）</div>
    <div v-for="group in sortRelease(releaseList)" :key="group.id" class="category-group">
      <div class="category-title leading-8 pt-[20px]">
        {{ group.title }} ({{ group.list.length }})
      </div>
      <ReleaseItem :newsData="{ records: group.list, total: group.list.length }" @remove="handleRemove"
        @moveUp="(id: any) => handleMove(id, 'up')" @moveDown="(id: any) => handleMove(id, 'down')">
        <img :src="arrowIcon" class="arrow-icon w-4 h-4" alt="arrow">
        <img :src="arrowIcon" class="arrow-icon w-4 h-4 rotate-180" alt="arrow">
      </ReleaseItem>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import ReleaseItem from './ReleaseItem.vue';
import { getReleaseList, updateNews } from '@/api/newspool';
import { tagEnums } from '@/enums';
import arrowIcon from '@/assets/circle-arrow.svg?url';
// import { getNewsList } from '@/api/newspublish';

const releaseList = ref<{ classReal: number; id: number, orderNews: number }[]>([]);

const handleRemove = async (id: number) => {
  const res = await updateNews({ id, isSelect: 0 });
  if (res.code === 200) {
    ElMessage.success('已成功移除！');
    releaseList.value = releaseList.value.filter(it => it.id !== id);
  }
};

const handleMove = (id: number, direction: 'up' | 'down') => {
  const groups = sortRelease(releaseList.value);
  let targetItem: any, targetGroup: any, itemIndex: any;

  for (const group of groups) {
    const index = group.list.findIndex(item => item.id === id);
    if (index !== -1) {
      targetItem = group.list[index];
      targetGroup = group;
      itemIndex = index;
      break;
    }
  }

  if (!targetItem || !targetGroup) return;
  const newIndex = direction === 'up' ? itemIndex! - 1 : itemIndex! + 1;
  if (newIndex < 0 || newIndex >= targetGroup.list.length) return;

  [targetGroup.list[itemIndex], targetGroup.list[newIndex]] = [targetGroup.list[newIndex], targetItem];
  const newList: any[] = [];
  groups.forEach(group => newList.push(...group.list));
  releaseList.value = newList;
};

const refresh = async () => {
  const res = await getReleaseList<{ list: { classReal: number; id: number }[] }>();
  releaseList.value = (res.data.list || []).map(item => ({
    ...item,
    orderNews: 0  // 添加默认的 orderNews 值
  }));

  sortRelease(releaseList.value);
};

// 获取排序接口数据
// const newsList = async () => {
//   try {
//     // 添加请求前的日志
//     console.log("开始请求排序接口");

//     const params = {
//       list: [] as {id: number; orderNews: number}[]
//     }

//     // 打印请求参数，确认参数是否正确
//     console.log("请求参数:", params);

//     const res = await getNewsList(params);

//     // 打印完整的响应结果
//     console.log("接口响应:", res);
//     console.log("获取排序接口数据", res.data);

//     return res;
//   } catch (error) {
//     console.error("请求失败:", error);
//   }
// }

const sortRelease = (list: { classReal: number; id: number, orderNews: number }[]) => {
  if (!list || !Array.isArray(list)) return [];

  const definedCategories = tagEnums.map(cat => cat.value);

  const undefinedItems = list.filter(it => !definedCategories.includes(it.classReal));

  const sorted = tagEnums.map(cat => ({
    id: cat.value,
    title: cat.label,
    list: list.filter(it => it.classReal === cat.value).sort((a, b) => a.orderNews - b.orderNews)
  }));

  if (undefinedItems.length > 0) {
    sorted.push({
      id: -1,
      title: "未分类",
      list: undefinedItems
    });
  }

  return sorted.filter(item => item.list.length > 0);
};

onMounted(async () => {
  const res = await getReleaseList<{ list: { classReal: number; id: number }[] }>();
  releaseList.value = (res.data.list || []).map(item => ({
    ...item,
    orderNews: 0  // 添加默认的 orderNews 值
  }));
  sortRelease(releaseList.value);
  // await newsList();
});
defineExpose({
  releaseList,
  refresh,
});

console.log(releaseList);
</script>

<style scoped>
.category-group {
  margin-bottom: 20px;
}

.category-title {
  padding: 8px 12px;
  color: #999;
  border-radius: 4px;
  margin-bottom: 10px;
  font-size: 14px;
  background-color: #f9fafb;
}

.arrow-icon {
  cursor: pointer;
  margin: 0 4px;
}
</style>